package com.zrq.secondkill.mq;

import com.alibaba.fastjson.JSON;
import com.zrq.secondkill.dao.StockLogDOMapper;
import com.zrq.secondkill.dataobject.StockLogDO;
import com.zrq.secondkill.enums.OrderStatusEnum;
import com.zrq.secondkill.error.BusinessException;
import com.zrq.secondkill.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.*;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class MqProducer {

    @Autowired
    OrderService orderService;

    private final StockLogDOMapper stockLogDOMapper;

    private TransactionMQProducer transactionMQProducer;

    @Value("${mq.nameserver.addr}")
    private String nameAddr;

    @Value("${mq.topicname}")
    private String topicName;

    private static final String PRODUCER_GROUP="producer_group1";

    public MqProducer(StockLogDOMapper stockLogDOMapper) {
        this.stockLogDOMapper = stockLogDOMapper;
    }


    @PostConstruct
    public void init() throws MQClientException {
        transactionMQProducer=new TransactionMQProducer();
        transactionMQProducer.setNamesrvAddr(nameAddr);
        transactionMQProducer.setVipChannelEnabled(false);
        transactionMQProducer.setProducerGroup(PRODUCER_GROUP);

        //设置producer
        transactionMQProducer.setTransactionListener(new TransactionListener() {
            @Override
            public LocalTransactionState executeLocalTransaction(Message msg, Object arg) {
                //真正要做的事  创建订单
                Map<String,Object> argMap= (Map<String, Object>) arg;

                Integer itemId = (Integer) argMap.get("itemId");
                Integer promoId = (Integer) argMap.get("promoId");
                Integer userId = (Integer) argMap.get("userId");
                Integer amount = (Integer) argMap.get("amount");
                String stockLogId = (String) argMap.get("stockLogId");

                try {
                    orderService.decreaseRedisStockAndWriteStockLog(userId,itemId,promoId,amount,stockLogId);
                } catch (BusinessException e) {
                    log.warn("redis库存扣减失败,准备将stockLog设为回滚状态并尝试回滚事务消息",e);

                    //假定消息队列是不可靠的,所以先将订单失败的信息持久化,若消息失败了,后续可以通过查持久化层的状态来再次尝试告知消息队列
                    //事务消息要提交还是回滚

                    //设置对应的stockLog为回滚状态
                    stockLogDOMapper.updateStatusByPrimaryKey(OrderStatusEnum.ROLLBACK.getStatus(), stockLogId);
                    return LocalTransactionState.ROLLBACK_MESSAGE;
                }
                return LocalTransactionState.COMMIT_MESSAGE;
            }

            @Override
            public LocalTransactionState checkLocalTransaction(MessageExt msg) {

                String jsonString  = new String(msg.getBody());

                Map<String,Object>map = JSON.parseObject(jsonString, Map.class);
                String stockLogId = (String) map.get("stockLogId");

                StockLogDO stockLogDO = stockLogDOMapper.selectByPrimaryKey(stockLogId);

                if(stockLogDO == null){
                    return LocalTransactionState.UNKNOW;
                }
                if(stockLogDO.getStatus() == OrderStatusEnum.SUCCESS.getStatus()){
                    return LocalTransactionState.COMMIT_MESSAGE;
                }else if(stockLogDO.getStatus() == OrderStatusEnum.UNCOMMITTED.getStatus()){
                    return LocalTransactionState.UNKNOW;
                }else {
                    return LocalTransactionState.ROLLBACK_MESSAGE;
                }
            }
        });

        transactionMQProducer.start();
    }

    /**
     * 先发送下单事务消息,然后redis尝试减库存,成功commit事务消息,失败回滚
     *
     * @param userId
     * @param itemId
     * @param promoId
     * @param amount
     * @param stockLogId
     * @return 创建订单是否成功
     */
    public boolean transactionalAsyncCreateOrder(Integer userId,Integer itemId,Integer promoId,Integer amount,String stockLogId){
        Map<String,Object> bodyMap = new HashMap<>(3);
        bodyMap.put("itemId",itemId);
        bodyMap.put("amount",amount);
        bodyMap.put("stockLogId",stockLogId);

        Map<String,Object> argsMap = new HashMap<>(5);
        argsMap.put("itemId",itemId);
        argsMap.put("amount",amount);
        argsMap.put("userId",userId);
        argsMap.put("promoId",promoId);
        argsMap.put("stockLogId",stockLogId);

        Message message = new Message(topicName,"increase",
                JSON.toJSON(bodyMap).toString().getBytes(StandardCharsets.UTF_8));

        TransactionSendResult sendResult;
        try {
            sendResult = transactionMQProducer.sendMessageInTransaction(message,argsMap);
        } catch (MQClientException e) {
            log.error("事务消息发送失败",e);
            return false;
        }

        return sendResult.getLocalTransactionState() == LocalTransactionState.COMMIT_MESSAGE;
    }

}
